<template>  
    <div class="overlay">  
      <div class="centered-content" v-clickoutside="handleOutside">  
        <!-- 这里可以放置你想要的内容 -->
        <div class="chatBox">
            <!-- <div class="userBox">
                <ul>
                    <li class="user-item">
                        <img class="img" src="../assets/avator/admin.jpg" alt="">
                        <div class="user-name">
                            <div>username</div>
                            <div>信息</div>
                        </div>
                        <div class="circle"></div>
                    </li>
                    <li class="user-item">
                        <img class="img" src="../assets/avator/admin.jpg" alt="">
                        <div class="user-name">
                            <div>username</div>
                            <div>信息</div>
                        </div>
                        <div class="circle"></div>
                    </li>
                </ul>
            </div> -->
            <div class="msgBox">
                <div class="msg-title" style="text-align: center; font-size: 24px;margin-bottom: 10px;">聊天</div>
                <hr/>
                <ul class="msg-ul" >
                    <!-- 左边的样式  -->
                        <li class="msg-item" v-for="(item,index) in messageList" :key="index">
                            <div :class="item.targetid == params.targetuserid?'li-box-right':'li-box'">
                                <img class="msg-img" :src="item.targetid == params.targetuserid?require('@/assets/avator/'+item.fromAvatar):require('@/assets/avator/'+item.targetAvatar)" alt="">
                                <div class="msg-content" v-html="analyzeEmoji(item.message)"></div><span style="font-size: 14px;">{{ item.time }}</span>
                            </div>
                        </li>
                </ul>
                <hr/>
                <div class="msg-input">
                    <!-- <input type="text" placeholder="请输入内容" class="msg-input-text"/> -->
                    <el-input
                        type="textarea"
                        :rows="5"
                        placeholder="请输入内容"
                        class="msg-input-text"
                        style="background-color: transparent;"
                        v-model="textarea"
                        >
                        </el-input>
                    <div class="msg-input-btn">
                        <el-button  size="mini" @click="showEmoj">Emoj</el-button>
                        <el-button class="submitBtn" type="primary" size="mini"  @click="sendMsg" >发送</el-button>
                    </div>
                </div>
                <!-- Emoji面板 -->
                <div v-show="showEmoji" class="emoji-panel" v-clickoutside="handleEmoOutside">
                  <!-- 这里放置Emoji面板的内容 -->
                  <ul class="OwO-items OwO-items-show">
                      <li
                        class="OwO-item"
                        v-for="(oitem, index) in OwOlist"
                        :key="'oitem' + index"
                        @click="choseEmoji(oitem.title)"
                      >
                        <img :src="require('@/assets/face/' + oitem.url)" alt="" />
                      </li>
                    </ul>
                </div>
            </div>
        </div>  
      </div>  
    </div>  
  </template>  
    
  <script>  
  import { mapMutations,mapActions } from 'vuex';
  import {GetMessageHistory} from '@/request/api'
  export default {  
    name: 'OverlayComponent',  
    data() {  
      return {  
        // 组件的数据可以在这里定义  
        textarea:'',
        socket:null,
        params:{
            targetuserid:this.$route.query.userid,
            fromuserid:null
        },
        messageList:[],
        isOwn:false,
        showEmoji:false,
        OwOlist: [
        //表情包和表情路径
        { title: "微笑", url: "weixiao.gif" },
        { title: "嘻嘻", url: "xixi.gif" },
        { title: "哈哈", url: "haha.gif" },
        { title: "可爱", url: "keai.gif" },
        { title: "可怜", url: "kelian.gif" },
        { title: "挖鼻", url: "wabi.gif" },
        { title: "吃惊", url: "chijing.gif" },
        { title: "害羞", url: "haixiu.gif" },
        { title: "挤眼", url: "jiyan.gif" },
        { title: "闭嘴", url: "bizui.gif" },
        { title: "鄙视", url: "bishi.gif" },
        { title: "爱你", url: "aini.gif" },
        { title: "泪", url: "lei.gif" },
        { title: "偷笑", url: "touxiao.gif" },
        { title: "亲亲", url: "qinqin.gif" },
        { title: "生病", url: "shengbing.gif" },
        { title: "太开心", url: "taikaixin.gif" },
        { title: "白眼", url: "baiyan.gif" },
        { title: "右哼哼", url: "youhengheng.gif" },
        { title: "左哼哼", url: "zuohengheng.gif" },
        { title: "嘘", url: "xu.gif" },
        { title: "衰", url: "shuai.gif" },
        { title: "吐", url: "tu.gif" },
        { title: "哈欠", url: "haqian.gif" },
        { title: "抱抱", url: "baobao.gif" },
        { title: "怒", url: "nu.gif" },
        { title: "疑问", url: "yiwen.gif" },
        { title: "馋嘴", url: "chanzui.gif" },
        { title: "拜拜", url: "baibai.gif" },
        { title: "思考", url: "sikao.gif" },
        { title: "汗", url: "han.gif" },
        { title: "困", url: "kun.gif" },
        { title: "睡", url: "shui.gif" },
        { title: "钱", url: "qian.gif" },
        { title: "失望", url: "shiwang.gif" },
        { title: "酷", url: "ku.gif" },
        { title: "色", url: "se.gif" },
        { title: "哼", url: "heng.gif" },
        { title: "鼓掌", url: "guzhang.gif" },
        { title: "晕", url: "yun.gif" },
        { title: "悲伤", url: "beishang.gif" },
        { title: "抓狂", url: "zhuakuang.gif" },
        { title: "黑线", url: "heixian.gif" },
        { title: "阴险", url: "yinxian.gif" },
        { title: "怒骂", url: "numa.gif" },
        { title: "互粉", url: "hufen.gif" },
        { title: "书呆子", url: "shudaizi.gif" },
        { title: "愤怒", url: "fennu.gif" },
        { title: "感冒", url: "ganmao.gif" },
        { title: "心", url: "xin.gif" },
        { title: "伤心", url: "shangxin.gif" }, 
        { title: "猪", url: "zhu.gif" },
        { title: "熊猫", url: "xiongmao.gif" },
        { title: "兔子", url: "tuzi.gif" },
        { title: "喔克", url: "ok.gif" },
        { title: "耶", url: "ye.gif" },
        { title: "棒棒", url: "good.gif" },
        { title: "不", url: "no.gif" },
        { title: "赞", url: "zan.gif" },
        { title: "来", url: "lai.gif" },
        { title: "弱", url: "ruo.gif" },
        { title: "草泥马", url: "caonima.gif" },
        { title: "神马", url: "shenma.gif" },
        { title: "囧", url: "jiong.gif" },
        { title: "浮云", url: "fuyun.gif" },
        { title: "给力", url: "geili.gif" },
        { title: "围观", url: "weiguan.gif" },
        { title: "威武", url: "weiwu.gif" },
        { title: "话筒", url: "huatong.gif" },
        { title: "蜡烛", url: "lazhu.gif" },
        { title: "蛋糕", url: "dangao.gif" },
        { title: "发红包", url: "fahongbao.gif" },
      ],
      // srcU:require('@/assets/face/')
      }  
    },
    methods:{
        ...mapMutations({
            setShowChat:'chatStatus/setShowChat' 
        }),
        ...mapActions({
            asyncChangeIsShowToast:'toastStatus/asyncChangeIsShowToast'
        }),
        // 消息提示
        open1() {
        this.$message({
          showClose: true,
          message: '内容不能为空'
        });
        },
        handleOutside(){
            this.setShowChat(false)
            // 关闭websocket连接
            // if (this.socket) {  
            //     this.socket.close();  
            //     this.socket = null;  
            // }  
        },
        handleEmoOutside(){
          this.showEmoji = false
        },
        async sendMsg(){
            if(this.textarea.trim()==''){
                this.open1()
            }else{
                if(this.socket.readyState === WebSocket.OPEN){
                    this.socket.send(this.textarea)
                    this.textarea = ''
                }else{
                    console.log("链接没打开")
                }
                // 更新页面数据
                let res = await GetMessageHistory(this.params)
                // console.log("@@@res.data.data",res.data.data)
                this.messageList = res.data.data
            }
        },
        async onMessageCallback(event){
            const msg = JSON.parse(event.data)
            // 刷新数据
            // console.log("收到消息的param",this.params)
            let res = await GetMessageHistory(this.params)
            this.messageList = res.data.data
            console.log("收到消息",msg)
        },
        showEmoj(){
          this.showEmoji = !this.showEmoji
        },
         //选择表情包
        choseEmoji: function (inner) {
         // 获取当前输入框的值
        let currentValue = this.textarea;
        // 在当前值的基础上添加选中的表情
        let newValue = currentValue + "[" + inner + "]";
        // 将新的值设置回输入框
        this.textarea = newValue;
        },
        analyzeEmoji: function (cont) {
      //编译表情替换成图片展示出来
      var pattern1 = /\[[\u4e00-\u9fa5]+\]/g;
      var pattern2 = /\[[\u4e00-\u9fa5]+\]/;
      var content = cont.match(pattern1);
      var str = cont;
      if (content) {
        for (var i = 0; i < content.length; i++) {
          for (var j = 0; j < this.OwOlist.length; j++) {
            if ("[" + this.OwOlist[j].title + "]" == content[i]) {
              var src = this.OwOlist[j].url;
              break;
            }
          }
          var s = require("@/assets/face/" + src);
          var imoj = "<img src='" + s + "'/>";

          str = str.replace(pattern2, imoj);
        }
      }
      return str;
        },
    },
     async created(){
        // 发送请求得到历史纪录
        this.textarea = ''
        this.params.fromuserid = sessionStorage.getItem("userid")
        let res = await GetMessageHistory(this.params)
        // console.log("get param",this.params)
        this.messageList = res.data.data
        // console.log("history data",res.data)
        // 开启websocket
        if(this.socket==null){
                // 创建websocket
                this.socket = new WebSocket('ws://localhost:8081/api/chat/'+this.params.targetuserid)
                // this.socket.onmessage = (event)=>{
                //     const msg = JSON.parse(event.data)
                //     console.log("收到信息",msg)
                // }
                this.socket.onmessage = this.onMessageCallback
                this.socket.onclose = ()=>{
                    this.params.targetuserid = this.$route.query.userid
                    this.params.fromuserid = sessionStorage.getItem("userid")
                    console.log("链接关闭")
                }
                // // 通过websocket发送消息\
                this.socket.onopen = ()=>{
                    console.log("链接开启")
                }
        }
    },
    
  }  
  </script>  
    
  <style scoped>  
  .overlay {  
    position: fixed;  
    top: 0;  
    left: 0;  
    width: 100%;  
    height: 100%;  
    background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */  
    display: flex;  
    justify-content: center;  
    align-items: center;  
  }  
  .centered-content {  
    background-color: #f5f5f5;  
    border-radius: 10px; /* 圆角 */  
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); /* 阴影 */  
    padding: 20px; /* 内边距 */  
    /* background-image: url('../assets/chatBackImg.jpg'); */
    /* background: linear-gradient(135deg, #a1c4fd, #c2e9fb); */
    background: linear-gradient(to top right, #a1c4fd, white);
  }  
  .chatBox{
      display: flex;
      flex-direction: row;
      width: 700px;
  }
  .userBox{
      flex: 3;
      margin-top: 30px;
  }
ul{
    list-style: none;
    padding: 0;
}
.user-item{
    display: flex;
    flex-direction: row;
    padding: 3px;
    position: relative;
    /* background-color: rgb(220, 218, 218); */
    border-radius: 5px;
    margin-bottom: 5px;
    margin-right: 5px;
    /* border: 1px solid gray; */
}
.user-item:hover{
    border: 1px solid gray;
    background-color: gray;
}
.img{
    width: 40px;
    height: 40px;
    border-radius: 3px;
}
.user-name{
    display: flex;
    flex-direction: column;
}
.circle{
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: red;
    position: absolute;
    right: -5px;
    top: -5px;
}

.msgBox{
      flex: 7;
      height: 500px;
      margin-top: 30px;
      position: relative;
      /* background-color: rgb(220, 218, 218); */
  }
  
  .msg-img{
    width: 40px;
    height: 40px;
    border-radius: 3px;
  }
  .msg-content{
    height: 30px;
    line-height: 30px;
    border-radius: 4px;
    /* margin-top: 5px; */
    margin-left: 3px;
    margin-right: 3px;
    background-color: rgb(102,177,255);
    color: white;
    padding: 5px 5px;
    display: flex;
    align-items: center;
  }
  .msg-ul{
    padding: 2px;
    height: 300px;
    overflow-y: scroll;
  }
  .msg-input-text{
    background-color: transparent !important;
    border: 0;
    width: 700px;
  }
  
  /* ::v-deep .birthday .el-input__inner {
  background-color: transparent !important; 
    } */
    .msg-input-btn{
        position: relative;
        margin-top: 3px;
    }
    .submitBtn{
        position: absolute;
        right: 5px;
    }
    .msg-item{
        margin-top: 5px;    
    }
    
    /* 左边对话框的样式 */
    .li-box{
        display: flex;
        flex-direction: row;
        vertical-align: middle;
    }
    span{
        display: inline-block;
        margin-top: 10px;
        color: skyblue;
        opacity: 0.7;
    }
    /* 右边对话框的样式 */
    .li-box-right{
        display: flex;
        flex-direction: row-reverse;
    }

    /* 滚动条样式
     */
     /* Webkit 浏览器（Chrome 和 Safari）滚动条样式 */
.msg-ul::-webkit-scrollbar {
  width: 10px;
}

.msg-ul::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.msg-ul::-webkit-scrollbar-thumb {
  background-color: #888;
  border-radius: 5px;
}

.msg-ul::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

/* 非 Webkit 浏览器滚动条样式 */
.msg-ul {
  scrollbar-width: thin;
  scrollbar-color: #888 #f1f1f1;
}

.msg-ul::-webkit-scrollbar {
  width: 10px;
}

.msg-ul::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.msg-ul::-webkit-scrollbar-thumb {
  background-color: #888;
  border-radius: 5px;
}

.msg-ul::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

.emoji-panel{
  /* height: 200px; */
  position: absolute;
  bottom: 35px;
  left: 0;
  background-color: white;
  padding: 5px;
  border-radius: 4px;
}

.OwO-items{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  box-sizing: border-box;
  justify-content: space-around;

}
.OwO-item{
  padding: 3px;
  border: 1px solid #ccc;
  background-color: bisque;
  cursor: pointer;
}
/* 使用伪元素辅助左对齐 */
.OwO-items::after {
    content: '';
    flex: auto;    /* 或者flex: 1 */
}
  </style>